package com.ldc.security.handler;

import com.ldc.common.state.StateCode;
import com.ldc.common.utils.ApiResponseUtils;
import com.ldc.model.base.ApiBean;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录失败
 *
 * @auther liudc
 * @since 2023/6/17
 */
@Component
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        ApiResponseUtils.writeObject(response, createFailedData(exception));
    }


    private ApiBean<Object> createFailedData(AuthenticationException authenticationException) {
        ApiBean<Object> data;
        if (authenticationException instanceof LockedException) {
            // 账户锁定
            data = ApiBean.result(StateCode.ACCOUNT_LOCKED);
        } else if (authenticationException instanceof CredentialsExpiredException) {
            // 密码过期
            data = ApiBean.result(StateCode.PASSWORD_EXPIRATION);
        } else if (authenticationException instanceof AccountExpiredException) {
            data = ApiBean.result(StateCode.ACCOUNT_EXPIRATION);
        } else if (authenticationException instanceof BadCredentialsException) {
            data = ApiBean.result(StateCode.ACCOUNT_OR_PASSWORD_ERROR);
        } else {
            data = ApiBean.result(StateCode.UNKNOWN_ERROR);
        }
        return data;

    }
}
